<?php

namespace App\Services;

use App\Subsidy;
use App\User;
use App\UsersOrders;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class SubService
{
    public $msg = '任务有误';
//    订单过期时间:30分钟
    const expired_time = 1800;

    /**
     * 发布任务
     * @param $max
     * @param $returnAmount
     * @param $goodType
     * @param $stores
     * @param $day
     * @param $dayCount
     * @param $uid
     * @param $id
     */
    public function addSub($max, $returnAmount, $goodType, $stores, $day, $dayCount, $uid, $id)
    {
        $stores = explode(',', $stores);
        if (!is_array($stores)) {
            $this->msg = '参数错误';
            return false;
        }

        try {
            //        开启事务
            DB::beginTransaction();
//          添加任务主表
            if ($id) {
//              更新任务
                $sub = DB::table('subsidy')->where('id', $id)->first();
                if (!$sub) throw new \Exception('该任务有误');
                // if ($sub->status == 1) throw new \Exception('该任务状态下无法修改');
                //更新主表
                $info = DB::table('stores')->where('id', $sub->store_id)->first();
                $update = [
                    'max_money' => $max,
                    'return_money' => $returnAmount,
                    'return_rate' => $returnAmount / $max,
                    'good_comment_type' => $goodType,
                    'day_count' => $day,
                    'single_day_count' => $dayCount,
                    'overdue' => date('Y-m-d', time() + 3600 * 24 * $day),
                    'current_rest' => $dayCount,
                    'updated_at' => date('Y-m-d H:i:s')
                ];
                if( $sub->status != 0 ){
                    $update['status'] = 1;
                }
                if( $info->status != 1 ){
                    $update['start_time'] = date('Y-m-d H:i:s');
                }
                DB::table('subsidy')->where('id', $id)->update($update);

            } else {
                //判断所选店铺是否正常
                foreach ($stores as $store) {
                    if (!$info = DB::table('stores_info')->join('stores', 'stores_info.store_id', '=', 'stores.id')
                        ->where('stores_info.id', intval($store))->where('stores.uid', $uid)->select(['stores_info.*', 'stores.status'])->first()) {
                        throw new \Exception('所选店铺异常');
                    }
                    $data = [
                        'uid' => $uid,
                        'max_money' => $max,
                        'return_money' => $returnAmount,
                        'return_rate' => $returnAmount / $max,
                        'good_comment_type' => $goodType,
                        'day_count' => $day,
                        'single_day_count' => $dayCount,
                        'start_time' => date('Y-m-d H:i:s'),
                        'overdue' => date('Y-m-d', time() + 3600 * 24 * $day),
                        'store_id' => $info->store_id,
                        'store_info_id' => $store,
                        'current_rest' => $dayCount,
                        'created_at' => date('Y-m-d H:i:s'),
                    ];
                    if( $info->status == 1 ){
                        $data['status'] = 1;
                    }
                    DB::table('subsidy')->insertGetId($data);
                }
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            $this->msg = $e->getMessage();
            return false;
        }

        return true;
    }

    /**
     * 创建订单
     * @param $uid
     * @param $subId
     * @param $orderId
     * @return bool
     */
    public function createOrder($uid, $subId, &$orderId): bool
    {
        $subsidyData = Subsidy::find($subId);
        if( !$subsidyData || $subsidyData->status != 1 || !$subsidyData->storesInfo || $subsidyData->is_frozen == 1 ){
            $this->msg = '任务已失效';
            return false;
        }
        //        用户信息
        $user = User::find($uid);
        if( !$user ){
            $this->msg = '用户信息错误';
            return false;
        }

        if( $user->status == 5 ){
            $this->msg = '您已被禁用，暂无法下单，请联系客服';
            return false;
        }

        if( DB::table('users_orders')->where('uid', $uid)->where('status', '<', 20)->count() ){
            $this->msg = '有进行中订单，无法再次下单!';
            return false;
        }

        $store = $subsidyData->stores;
        $startTimes = explode(':', $store->start_time);
        $endTimes = explode(':', $store->end_time);
        if( $store->start_time != $store->end_time ){
            if( intval($startTimes[0]) > intval($endTimes[0]) ){
                //凌晨营业
                if( intval($startTimes[0]) > intval(date('H')) && intval($endTimes[0]) <= intval(date('H')) ){
                    $this->msg = '当前时间店铺未营业';
                    return false;
                }
            }else{
                //一天正常营业
                if( intval($startTimes[0]) > intval(date('H')) || ( intval($startTimes[0]) == intval(date('H')) && intval($startTimes[1]) > intval(date('i')) ) ){
                    $this->msg = '当前时间店铺还未开始营业';
                    return false;
                }
                
                if( intval($endTimes[0]) < intval(date('H')) || ( intval($endTimes[0]) == intval(date('H')) && intval($endTimes[1]) < intval(date('i'))) ){
                    $this->msg = '店铺今日营业时间已结束';
                    return false;
                }
            }
        }
        

        if( $subsidyData->current_rest <= 0 ){
            $this->msg = '产品已售罄';
            return false;
        }
        $fee = DB::table('config')->where('key', 'fee')->value('value');
        $fee = $fee ?? 2;
        $discount = DB::table('fee_activity')->where('start', '<', getDt())->where('end', '>', getDt())->orderBy('id', 'desc')->value('discount');
        $realFee = $discount != null ? round($fee * $discount/10, 2) : $fee;

        try {
            DB::beginTransaction();
//            减少库存
            DB::table('subsidy')->where('id', $subId)->where('current_rest', '>', 0)->decrement('current_rest');
//          添加订单
            $UsersOrdersModel = new UsersOrders();
            $UsersOrdersModel->uid = $uid;
            $UsersOrdersModel->sub_id = $subId;
            $UsersOrdersModel->store_uid = $subsidyData->uid;
            $UsersOrdersModel->store_id = $subsidyData->store_id;
            $UsersOrdersModel->store_info_id = $subsidyData->store_info_id;
            $UsersOrdersModel->order_no = getOrderNo($uid, 1);//订单号
            $UsersOrdersModel->store_title = $subsidyData->storesInfo->title;
            $UsersOrdersModel->good_comment_type = $subsidyData->good_comment_type;
            $UsersOrdersModel->store_img = $store->imgurl;
            $UsersOrdersModel->max_money = $subsidyData->max_money;
            $UsersOrdersModel->return_money = $subsidyData->return_money;
            $UsersOrdersModel->real_return_money = $user->vip_status == 1 ? $subsidyData->return_money : round($subsidyData->return_money * 0.8, 2); //实际返现金额
            $UsersOrdersModel->overdue = date('Y-m-d H:i:s', time() + self::expired_time);
            $UsersOrdersModel->fee = $fee;
            $UsersOrdersModel->discount_fee = $fee - $realFee;
            $UsersOrdersModel->settle_amount = $UsersOrdersModel->return_money + $realFee;
            $UsersOrdersModel->save();
            $orderId = $UsersOrdersModel->id;
            //更新最近下单时间
            DB::table('users')->where('id', $uid)->update(['last_order_time'=>getDt(), 'updated_at'=>getDt()]);
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            $this->msg = "下单人数过多，请稍后再试";
            return false;
        }

        return true;
    }

    /**
     *
     * @param $uid
     * @param $orderId
     * @return bool
     */
    public function cancelOrder($uid, $orderId): bool
    {
        $order = UsersOrders::find($orderId);
        if( !$order || ($order->status != 0 && $order->status != 10) ){
            $this->msg = '订单无法取消';
            return false;
        }
        if( $order->uid != $uid ){
            $this->msg = '您无权限取消该订单';
            return false;
        }

        try {
            DB::beginTransaction();
//            返回库存
            DB::table('subsidy')->where('id', $order->sub_id)->increment('current_rest');
//          添加订单
            $order->status = 60;
            $order->save();
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            $this->msg = "请稍后再试";
            return false;
        }
        return true;

    }

    /**
     * 检查当前任务最新订单状态
     */
    public function checkSubOrder($uid, $subId, &$orderId){
        $order = \DB::table('users_orders')->where([['uid', $uid],['sub_id', $subId],['status', 0]])->first();
        if( !$order ){
            return false;
        }

        $orderId = $order->id;
        return true;
    }
}